 package com.example.safeassistan.risk.fragment;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseModel;
import com.example.safeassistan.base.BaseVPFragment;
import com.example.safeassistan.common.UserData;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.home.activity.ActivityBacklogList;
import com.example.safeassistan.home.activity.ActivityBacksecond;
import com.example.safeassistan.home.activity.ActivityCheckLog;
import com.example.safeassistan.home.activity.HiddenDangerinvestigation;
import com.example.safeassistan.home.activity.RiskPointDetail;
import com.example.safeassistan.home.activity.RiskPointList;
import com.example.safeassistan.home.activity.WarnningList;
import com.example.safeassistan.home.adapter.BackLogAdapter;
import com.example.safeassistan.home.adapter.RiskPointAdapter;
import com.example.safeassistan.home.fragment.RiskDetailBasicInfoFragment;
import com.example.safeassistan.home.fragment.RiskDetailCheckLogFragment;
import com.example.safeassistan.home.fragment.RiskDetailHiddendangerFragment;
import com.example.safeassistan.home.fragment.RiskDetailInstructionFragment;
import com.example.safeassistan.home.fragment.RiskDetailPersonFragment;
import com.example.safeassistan.home.fragment.RiskDetailRiskFragment;
import com.example.safeassistan.home.fragment.RiskDetailTableFragment;
import com.example.safeassistan.home.model.BackLogFragmentModel;
import com.example.safeassistan.home.model.MyBackLogListModel;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.login.activity.LoginPasswordActivity;
import com.example.safeassistan.risk.adapter.RiskMyListAdapter;
import com.example.safeassistan.risk.model.RiskPointDetailModel;
import com.example.safeassistan.risk.model.RiskPointLevelStatModel;
import com.example.safeassistan.risk.model.RiskPointListSearchModel;
import com.example.safeassistan.risk.model.WarnningModel;
import com.example.safeassistan.train.activity.ActivityTrainResult;
import com.example.safeassistan.train.model.PaperResultModel;
import com.example.safeassistan.utile.JsonUtils;
import com.google.android.material.tabs.TabLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.safeassistan.common.MethodUtils.getUserId;
import static com.example.safeassistan.constants.Constants.PAGESIZE;

 public class RiskMyFragment extends BaseVPFragment implements View.OnClickListener {
    private Context context;
    private View view;
    private TextView tvBackLogCount;
    private RiskMyListAdapter adapter;
    private BackLogAdapter backLogAdapter;
    private List<RiskPointListSearchModel.ResultDTO.RecordsDTO> data;
    private RecyclerView rcView,rcBackLog;
    private LinearLayout llbacklog;
    private int type=0;
    private TextView tvMore,tvDegree,tvStatus,tvTip;
    private SmartRefreshLayout refresh;
    private TextView tvBigRisk,tvBiggerRisk,tvRiskCommon,tvRiskLow,tvRiskTotal;
    private LinearLayout llSearch,llDegree,llStatus,llWarnning;
    private int riskLevel=-1;//风险等级
     private int isOutOfControl=-1;//是否受控
     private int currentPage=1;
     private int count=0;

    public static RiskMyFragment newInstance(int  type) {
        Bundle arguments = new Bundle();
        arguments.putInt("type",type);
        RiskMyFragment fl = new RiskMyFragment();
        fl.setArguments(arguments);
        return fl;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.risk_my_fragment, container, false);
            context = getActivity();
            initView();
        }
        return view;
    }

    public void initView(){
        Bundle bundle = getArguments();
         type = bundle.getInt("type");
        tvBigRisk=view.findViewById(R.id.tvBigRisk);
        llbacklog=view.findViewById(R.id.llbacklog);
        rcView=view.findViewById(R.id.rcView);
        rcBackLog=view.findViewById(R.id.rcBackLog);
        refresh=view.findViewById(R.id.refresh);
        tvMore=view.findViewById(R.id.tvMore);
        llSearch=view.findViewById(R.id.llSearch);
        tvBackLogCount=view.findViewById(R.id.tvBackLogCount);
        llStatus=view.findViewById(R.id.llStatus);
        llDegree=view.findViewById(R.id.llDegree);
        tvRiskLow=view.findViewById(R.id.tvRiskLow);
        tvDegree=view.findViewById(R.id.tvDegree);
        tvTip=view.findViewById(R.id.tvTip);
        llWarnning=view.findViewById(R.id.llWarnning);
        tvStatus=view.findViewById(R.id.tvStatus);
        tvRiskTotal=view.findViewById(R.id.tvRiskTotal);
        tvRiskCommon=view.findViewById(R.id.tvRiskCommon);
        tvBiggerRisk=view.findViewById(R.id.tvBiggerRisk);
        llStatus.setOnClickListener(this::onClick);
        llSearch.setOnClickListener(this::onClick);
        llDegree.setOnClickListener(this::onClick);
        tvMore.setOnClickListener(this);
        rcView.setNestedScrollingEnabled(false);
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        if (isVisible){
            getWarnning();
            getTopData();
        }
    }

    @Override
    protected void onFragmentFirstVisible() {
        setView();
        getMidData();
        getData();
    }

    PopupWindow popupWindow=null;
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.llDegree:
                View inflate1 = LayoutInflater.from(context).inflate(R.layout.popu_risk_level,null);
                TextView tvAll=inflate1.findViewById(R.id.tvAll);
                tvAll.setWidth(llDegree.getWidth());
                tvAll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        riskLevel=-1;
                        popupWindow.dismiss();
                        tvDegree.setText("风险等级");
                        tvDegree.setTextColor(context.getResources().getColor(R.color.gray3));
                        getData();
                        getMidData();
                    }
                });
                TextView tvBig=inflate1.findViewById(R.id.tvBig);
                tvBig.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        riskLevel=1;
                        popupWindow.dismiss();
                        tvDegree.setText("重大风险");
                        tvDegree.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                        getMidData();
                    }
                });
                TextView tvBigger=inflate1.findViewById(R.id.tvBigger);
                tvBigger.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        riskLevel=2;
                        popupWindow.dismiss();
                        tvDegree.setText("较大风险");
                        tvDegree.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                        getMidData();
                    }
                });
                TextView tvCommon=inflate1.findViewById(R.id.tvCommon);
                tvCommon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        riskLevel=3;
                        popupWindow.dismiss();
                        tvDegree.setText("一般风险");
                        tvDegree.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                        getMidData();
                    }
                });
                TextView tvLow=inflate1.findViewById(R.id.tvLow);
                tvLow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        riskLevel=4;
                        popupWindow.dismiss();
                        tvDegree.setText("较低风险");
                        tvDegree.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                        getMidData();
                    }
                });
                popupWindow = new PopupWindow(inflate1, RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(llDegree,0,-100);
                break;
            case R.id.llStatus:
                View inflate = LayoutInflater.from(context).inflate(R.layout.popu_risk_status,null);
                TextView tvStatu=inflate.findViewById(R.id.tvStatus);
                tvStatu.setWidth(llStatus.getWidth());
                tvStatu.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        isOutOfControl=-1;
                        popupWindow.dismiss();
                        tvStatus.setText("状态");
                        tvStatus.setTextColor(context.getColor(R.color.gray3));
                        getData();
                        getMidData();
                    }
                });

                TextView tvControl=inflate.findViewById(R.id.tvControl);
                tvControl.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        isOutOfControl=0;
                        popupWindow.dismiss();
                        tvStatus.setText("受控");
                        tvStatus.setTextColor(context.getColor(R.color.blue_3B5BEA));
                        getData();
                        getMidData();
                    }
                });

                TextView tvEarlyWarrning=inflate.findViewById(R.id.tvEarlyWarrning);
                tvEarlyWarrning.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        isOutOfControl=1;
                        popupWindow.dismiss();
                        tvStatus.setText("预警");
                        tvStatus.setTextColor(context.getColor(R.color.blue_3B5BEA));
                        getData();
                        getMidData();
                    }
                });
                popupWindow = new PopupWindow(inflate, RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(llStatus,0,-100);
                break;
            case R.id.tvMore:
                WarnningList.actionStart(context,"0","");
                break;
            case R.id.llSearch:
                //搜索风险点
                RiskPointList.actionStart(context,1);
                break;
        }
    }

     public void setView(){
         data=new ArrayList<>();
         refresh.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
         refresh.setOnRefreshListener(new OnRefreshListener() {
             @Override
             public void onRefresh(final RefreshLayout refreshLayout) {
                 refreshLayout.getLayout().postDelayed(new Runnable() {
                     @Override
                     public void run() {
                         currentPage = 1;
                        getData();
                        getTopData();
                     }
                 }, 1000);
             }
         });
         refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
             @Override
             public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                 refreshLayout.getLayout().postDelayed(new Runnable() {
                     @Override
                     public void run() {
                         currentPage++;
                         getData();
                     }
                 }, 1000);
             }
         });
     }

    // 获取数据
     public void getData(){
         JSONObject map = new JSONObject();
         try {
             map.put("pageNo", String.valueOf(currentPage));
             map.put("pageSize",String.valueOf(PAGESIZE));
             map.put("selectType",String.valueOf(1));//选择类型 1 我的 2 部门
             if (isOutOfControl!=-1){
                 map.put("isOutOfControl",isOutOfControl);//是否受控
             }
             if (riskLevel!=-1){
                 map.put("riskLevel",riskLevel);//风险等级
             }
         } catch (JSONException e) {
             e.printStackTrace();
         }

         new HttpRequest(context).doPost(UrlConstants.getRiskList, null, map, new HttpStringCallBack() {
             @RequiresApi(api = Build.VERSION_CODES.M)
             @Override
             public void onSuccess(Object result) {
                 String datas = result.toString();
                 JSONObject jsonObject = null;
                 try {
                     jsonObject = new JSONObject(datas);
                     String message = jsonObject.getString("message");
                     Boolean success = jsonObject.getBoolean("success");
                     if (success) {
                         Object obj = JsonUtils.fromJson(result.toString(), RiskPointListSearchModel.class);
                         if (obj instanceof RiskPointListSearchModel) {
                             RiskPointListSearchModel model=(RiskPointListSearchModel) obj;
                             if (currentPage == 1) {
                                 data.clear();
                                 count = model.getResult().getTotal();
                                 if (model.getResult().getRecords().size() > 0) {
                                     data=model.getResult().getRecords();
                                     adapter=new RiskMyListAdapter(data);
                                     rcView.setNestedScrollingEnabled(true);
                                     rcView.setLayoutManager(new LinearLayoutManager(context));
                                     rcView.setAdapter(adapter);
                                     if (adapter.getItemCount() < count) {
                                         //还有多的数据
                                         refresh.finishRefresh();
                                     } else {
                                         //没有更多数据（上拉加载功能将显示没有更多数据）
                                         refresh.finishRefreshWithNoMoreData();
                                     }
                                     adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                         @Override
                                         public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                             RiskPointDetail.actionStart(getContext(),data.get(position).getId(),riskLevel,"0");
                                         }
                                     });
                                 } else {
                                     refresh.finishRefreshWithNoMoreData();
                                     adapter.notifyDataSetChanged();
                                 }
                             } else {
                                 data.addAll(model.getResult().getRecords());
                                 adapter.notifyDataSetChanged();
                                 if (adapter.getItemCount() < count) {
                                     //还有多的数据
                                     refresh.finishLoadMore();
                                 } else {
                                     //没有更多数据（上拉加载功能将显示没有更多数据）
                                     refresh.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                                 }
                             }
                         }
                     }else {
                         Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                     }
                 }catch (Exception e){
                     e.printStackTrace();
                 }
             }

             @Override
             public void onFailure(int code, String msg) {
                 refresh.finishLoadMore();
                 refresh.finishRefresh();
             }
         });
     }


     public void getMidData(){
         JSONObject object=new JSONObject();
         try {
             if(riskLevel!=-1){
                 object.put("riskLevel",riskLevel);//风险等级
             }
             object.put("selectType",String.valueOf(1));//搜索类型 1 我的 2 部门
             if (isOutOfControl!=-1){
                 object.put("isOutOfControl",String.valueOf(isOutOfControl));//是否受控
             }
         } catch (JSONException e) {
             e.printStackTrace();
         }


         new HttpRequest(context).doPost(UrlConstants.getPointLevelStat, null, object,new HttpStringCallBack() {
             @RequiresApi(api = Build.VERSION_CODES.M)
             @Override
             public void onSuccess(Object result) {
                 String datas = result.toString();
                 JSONObject jsonObject = null;
                 try {
                     jsonObject = new JSONObject(datas);
                     String message = jsonObject.getString("message");
                     int  code = jsonObject.getInt("code");
                     if (code==200) {
                         Object obj = JsonUtils.fromJson(result.toString(), RiskPointLevelStatModel.class);
                         if (obj instanceof RiskPointLevelStatModel) {
                             RiskPointLevelStatModel  riskPointLevelStatModel=(RiskPointLevelStatModel) obj;
                             tvBigRisk.setText(riskPointLevelStatModel.getResult().getRiskLevel1()+"");
                             tvBiggerRisk.setText(riskPointLevelStatModel.getResult().getRiskLevel2()+"");
                             tvRiskCommon.setText(riskPointLevelStatModel.getResult().getRiskLevel3()+"");
                             tvRiskLow.setText(riskPointLevelStatModel.getResult().getRiskLevel4()+"");
                             tvRiskTotal.setText(riskPointLevelStatModel.getResult().getTotal()+"");
                         }else {
                             Log.e("aaaa","哈哈哈哈哈");
                         }
                     }else {
                         Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                     }
                 }catch (Exception e){
                     e.printStackTrace();
                 }
             }

             @Override
             public void onFailure(int code, String msg) {
             }
         });
     }

     public void getTopData(){
         new HttpRequest(context).doGet(UrlConstants.getMyTaskList, null, new HttpStringCallBack() {
             @RequiresApi(api = Build.VERSION_CODES.M)
             @Override
             public void onSuccess(Object result) {
                 String datas = result.toString();
                 JSONObject jsonObject = null;
                 try {
                     jsonObject = new JSONObject(datas);
                     String message = jsonObject.getString("message");
                     int  code = jsonObject.getInt("code");
                     if (code==200) {
                         Object obj = JsonUtils.fromJson(result.toString(), MyBackLogListModel.class);
                         if (obj instanceof MyBackLogListModel) {
                             MyBackLogListModel  backLogListModel=(MyBackLogListModel) obj;
                             if (backLogListModel.getResult().size()>0){
                                 tvBackLogCount.setText(backLogListModel.getResult().size()+"");
                                 llbacklog.setVisibility(View.VISIBLE);
                                 rcBackLog.setVisibility(View.VISIBLE);
                                 rcBackLog.setLayoutManager(new LinearLayoutManager(context));
                                 backLogAdapter=new BackLogAdapter(backLogListModel.getResult());
                                 rcBackLog.setAdapter(backLogAdapter);
                                 backLogAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                     @Override
                                     public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                         if (backLogListModel.getResult().get(position).getType()==1){
                                             ActivityBacksecond.actionStart(context,backLogListModel.getResult().get(position).getId(),
                                                     backLogListModel.getResult().get(position).getCheckTableId());
                                         }else {
                                             List<BackLogFragmentModel.ResultDTO.RecordsDTO.DangerVOListDTO> list=new ArrayList<>();
                                             BackLogFragmentModel.ResultDTO.RecordsDTO.DangerVOListDTO m=new BackLogFragmentModel.ResultDTO.RecordsDTO.DangerVOListDTO();
                                             m.setSelect(true);
                                             m.setId("");
                                             m.setDangerSrcName("");
                                             list.add(m);
                                             HiddenDangerinvestigation.actionStart(1,context,backLogListModel.getResult().get(position).getId(),
                                                     backLogListModel.getResult().get(position).getRiskPointName(),1,
                                                     backLogListModel.getResult().get(position).getRiskPointId()
                                                     ,backLogListModel.getResult().get(position).getCheckTableId(),list);
                                         }
                                     }
                                 });
                             }else {
                                 llbacklog.setVisibility(View.GONE);
                                 rcBackLog.setVisibility(View.GONE);
                             }
                         }
                     }else if (message.equals("操作失败，请登录")){
                         LoginPasswordActivity.actionStart(context,"");
                     }else {
                         Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                     }
                 }catch (Exception e){
                     e.printStackTrace();
                 }
             }

             @Override
             public void onFailure(int code, String msg) {
             }
         });
     }

     public void getWarnning(){
        Map map=new HashMap<>();
        map.put("checkStatus","0");

         new HttpRequest(context).doGet(UrlConstants.risk_queryWarnRiskPointCount, null,map ,new HttpStringCallBack() {
             @RequiresApi(api = Build.VERSION_CODES.M)
             @Override
             public void onSuccess(Object result) {
                 String datas = result.toString();
                 JSONObject jsonObject = null;
                 try {
                     jsonObject = new JSONObject(datas);
                     String message = jsonObject.getString("message");
                     Boolean  success = jsonObject.getBoolean("success");
                     if (success) {
                         Object obj = JsonUtils.fromJson(result.toString(), WarnningModel.class);
                         if (obj instanceof WarnningModel) {
                             WarnningModel model=(WarnningModel)obj;
                                if (model.getResult()==0){
                                    llWarnning.setVisibility(View.GONE);
                                }else {
                                    llWarnning.setVisibility(View.VISIBLE);
                                    tvTip.setText("有"+model.getResult()+"个风险点在预警状态");
                                }
                         }
                     }else {
                         Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                     }
                 }catch (Exception e){
                     e.printStackTrace();
                 }
             }

             @Override
             public void onFailure(int code, String msg) {
             }
         });
     }
}